package com.xu.base.utils;

import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.support.WebClientAdapter;
import org.springframework.web.service.invoker.HttpServiceProxyFactory;

/**
 * web interface工具
 *
 * @Author: 许乾伟
 * @Date: 2024/12/6 14:49
 */
public class WebInterfaceUtils<T> {
    /**
     * 构建一个web客户端
     * @param clazz 客户端类
     *      // api定义类示例
     *      @HttpExchange("http://localhost:8080/test")
     *      public interface UserClient {
     *          //接口定义示例
     *          @GetExchange("/getUser")
     *          CurrentUserVo getUser();
     *      }
     *      //使用
     *      UserClient userClient = WebInterfaceUtils.createWebClient("http://localhost:8080",UserClient.class);
     * @return
     * @param <T>
     */
    public <T> T createWebClient(Class<T> clazz){
        //构建一个web客户端
        WebClient webClient = WebClient.builder().build();
        //根据web客户端去构建服http服务的代理工厂
        HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(WebClientAdapter.create(webClient)).build();
        //创建代理客户端
        return factory.createClient(clazz);
    }
    /**
     * 构建一个web客户端
     * @param baseUrl 接口请求根路径
     * @param clazz 客户端类
     *      // api定义类示例
     *      @HttpExchange("/test")
     *      public interface UserClient {
     *          //接口定义示例
     *          @GetExchange("/getUser")
     *          CurrentUserVo getUser();
     *      }
     *      //使用
     *      UserClient userClient = WebInterfaceUtils.createWebClient("http://localhost:8080",UserClient.class);
     * @return
     * @param <T>
     */
    public <T> T createWebClient(String baseUrl,Class<T> clazz){
        //构建一个web客户端
        WebClient webClient = WebClient.builder().baseUrl(baseUrl).build();
        //根据web客户端去构建服http服务的代理工厂
        HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(WebClientAdapter.create(webClient)).build();
        //创建代理客户端
        return factory.createClient(clazz);
    }
}
